package team.shixi.houtai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import team.shixi.houtai.common.Result;
import team.shixi.houtai.common.ResultUtil;
import team.shixi.houtai.entity.Goods;
import team.shixi.houtai.mapper.GoodsMapper;
import team.shixi.houtai.service.GoodsService;

import java.time.LocalDateTime;

/**
 * @author Zhangrt
 * @Description
 * @create 2023-01-10 17:06
 */
@Slf4j
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsMapper goodsMapper;
    
    @PostMapping//新增数据
    public Result<?> save(@RequestBody Goods goods){
        goods.setStatus(0);
        goods.setTime(LocalDateTime.now());
        goodsService.save(goods);
        return Result.success();
    }
    @PutMapping//更新数据
    public Result<?> update(@RequestBody Goods goods){
        goodsService.updateById(goods);
        return Result.success();
    }
    @PutMapping("/{id}")//上/下商品
    public Result<?> updowngoods(@PathVariable Long id){
        Goods goods = goodsService.getById(id);

        if (goods.getStatus() == 0){
            //未上架
            goods.setStatus(1);//上架
        }else{
            //上架
            goods.setStatus(0);//下架
        }
        goodsService.updateById(goods);
        return Result.success();
    }
    @DeleteMapping("/{id}")//删除数据
    public Result<?> delete(@PathVariable Long id){
        goodsService.removeById(id);
        return Result.success();
    }
    @GetMapping//查询数据
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){

        Page<Goods> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like((StringUtils.isNotBlank(search)),Goods::getGname,search);
        Page<Goods> goodsPage = goodsMapper.selectAllPage(page, queryWrapper);

        return ResultUtil.success(goodsPage);

    }
}
